package com.etoak.controller;

import com.etoak.entity.User;
import com.etoak.service.UserService;
import com.etoak.util.ValidatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {

    @Autowired
    UserService service;
    /*public static final Logger log = LoggerFactory.getLogger(UserController.class);*/

    /**
     * 查询用户接口 get  /user/get?id=1
     * @param id
     * @return
     */
    @GetMapping("/get")
    public User getUser(int id) {
        return service.getUser(id);
    }

    /**
     * Rest风格查询用户接口
     */
    @GetMapping("/{id}")
    public User getRestUser(@PathVariable int id) {
        log.info("id is {}",id);

        return service.getUser(id);
    }

    /**
     * 添加用户
     * POST  /user
     */
    @PostMapping
    public Object addUser(@RequestBody User user) {
        log.info("user - {}",user);

        Map<String,Object> map = new HashMap<>();

        //校验
        try {
            ValidatorUtil.validate(user);
        } catch (RuntimeException e) {
          log.error(e.getMessage(),e);

          map.put("code",201);
          map.put("msg",e.getMessage());

          return map;
        }

        map.put("code",200);
        map.put("msg","success");
        return map;
    }

    /**
     * 修改用户信息
     *
     */
    @PutMapping("/{id}")
    public Object updateUser(@PathVariable int id,@RequestBody User user){
        Map<String,Object> map = new HashMap<>();

        //先根据id查询是否有用户存在
        User us = service.getUser(id);
        if(us == null){
            map.put("code",201);
            map.put("msg","没有这个用户");
        }


        System.out.println("id=" + id);
        System.out.println("user=" + user);


        map.put("code",200);
        map.put("msg","success");
        return map;
    }

    /**
     * 根据id删除用户
     *
     */
    @DeleteMapping("/{id}")
    public Object delUser(@PathVariable int id){
        Map<String,Object> map = new HashMap<>();

        System.out.println("id=" + id);

        map.put("code",200);
        map.put("msg","success");
        return map;
    }


}
